<template>
  <div class="item" v-for="book in books" :key="book.id">
    <figure>
      <router-link :to="'/book/' + book.id">
        <img :src="book.imgUrl" alt="" />
        <figcaption>
          <h3>{{ book.title }}</h3>
        </figcaption>
      </router-link>
    </figure>
    <p>
      {{ currency(factPrice(book.price, book.discount)) }}
      <span>
        {{ currency(book.price) }}
      </span>
    </p>
  </div>
</template>

<script>
import { onMounted, onUnmounted, ref } from "vue";
import axios from "axios";
export default {
  name: "ListItem",
  inject: ["factPrice", "currency"],

  setup() {
    // 创建响应式的books数组接受axios请求拿到的数据
    let books = ref([]);
    // 设置一个值判断是否正在请求数据
    let loading = false;
    // 定义一个方法判断滚动条位置，判断是否加载数据
    function scrollHandle() {
      const scrollHeight = document.body.scrollHeight;
      const scrollTop =
        document.body.scrollTop || document.documentElement.scrollTop;
      const clientHeight = document.documentElement.clientHeight;

      const distance = scrollHeight - scrollTop - clientHeight;
      if (distance <= 200) {
        load();
      }
    }
    // 在实例挂载时对滚动条绑定监听事件
    onMounted(() => {
      window.addEventListener("scroll", scrollHandle);
    });
    // 在实例卸载时移除监听事件
    onUnmounted(() => {
      window.removeEventListener("scroll", scrollHandle);
    });
    // 定义发送axios请求数据的方法
    function load() {
      if (loading) return;
      loading = true;
      axios
        .get("/book/new")
        .then((res) => {
          if (res.status == 200) {
            books.value = books.value.concat(res.data);
            loading = false;
          }
        })
        .catch((error) => console.log(error));
    }
    //  执行axios请求
    load();
    // 返回一个对象，里面books有axios请求到的数据
    return {
      books,
    };
  },
};
</script>

<style>
.item {
  display: flex;
  margin: 36px;
  text-align: center;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
  border-radius: 30px;
  width: 28%;
  padding: 30px;
  border: 1px solid #ccc;
  transition: 0.8s;
}
.item:hover {
  margin: 20px 36px 52px 36px;
  box-shadow: 0 5px 10px 4px rgb(196, 195, 195);
}
a {
  text-decoration-line: none;
}
.item h3 {
  font-size: 22px;
  overflow: hidden;
}
.item span {
  color: #ccc;
  font-size: 14px;
  line-height: 26px;
  text-decoration: line-through;
  height: 78px;
  overflow: hidden;
}
.item p {
  color: rgb(0, 0, 0);
  font-size: 20px;
}
</style>
